package com.rainsoftware.LicenseSystem.services;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rainsoftware.LicenseSystem.models.entity.SystemUser;
import com.rainsoftware.LicenseSystem.utils.JwtUtil;
import com.rainsoftware.LicenseSystem.utils.StandardResponse;
import gaarason.database.contract.eloquent.Record;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@Service
public class UserService {
    @Autowired
    private SystemUser.Model sysUserModel;

    private UserService() {
    }


    @Getter
    private SystemUser systemUser;

    public SystemUser parseUser(String token) {
        int uuid = JwtUtil.extractUserId(token);

        Record<SystemUser, Integer> record = sysUserModel.find(uuid);
        if (record == null) {
            return null;
        }
        return systemUser = record.getEntity();
    }

    public static void generateResponse(HttpServletResponse response, StandardResponse result) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        String str = String.valueOf(result.build().getBody());
        writer.print(str);
        writer.close();
        response.flushBuffer();
    }
}
